﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;
using System.Data.Common;
using System.Data.EntityClient;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace MINERP.DAL.CustomerManage
{
    /// <summary>
    /// 与开单有关的数据库操作
    /// </summary>
    public class StartOrderDAL
    {
        //属性
        public newSampleYPDBEntities DataEntites = new newSampleYPDBEntities();
        //public newSampleYPDBEntities entity = DataEntites;
        // public string conStr = ConfigurationManager.ConnectionStrings["fffff"].ToString();
        public string conStr = DALBase.ConnStr;
        SqlConnection con;

        public ObjectQuery<Tb_Product> GetProduct()
        {
            try
            {
                return DataEntites.Tb_Product.Where("true").Include("Tb_PorductCategory").Include("paperType").Include("paperFace").Include("tb_ProductType");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region 判断订单包号是否已存在
        /// <summary>
        /// 判断订单包号是否已存在
        /// </summary>
        /// <param name="bagCode"></param>
        /// <returns></returns>
        public bool IsOrderBagExist(string bagCode)
        {
            try
            {
                string esql = "select value count(1) from Tb_OrderBag as it where it.BagCode='" + bagCode + "'";
                ObjectQuery<int> nums = DataEntites.CreateQuery<int>(esql);
                if (nums == null || nums.Count() == 0)
                {
                    return false;
                }
                else
                {
                    int num = nums.First();
                    if (num > 0)
                        return true;
                    else
                        return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        /// <summary>
        /// 获取开单人
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public users GetStartOrderUser(int userid)
        {
            try
            {
                return DataEntites.users.Where("it.userID=" + userid).First();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取所有的产品流程
        /// </summary>
        public List<Tb_FlowTemplate> GetProductFlow()
        {
            try
            {
                if (DataEntites.Connection.State != System.Data.ConnectionState.Open)
                    DataEntites.Connection.Open();
                List<Tb_FlowTemplate> ftList = new List<Tb_FlowTemplate>();
                ObjectQuery<Tb_FlowTemplate> query = DataEntites.Tb_FlowTemplate;

                foreach (Tb_FlowTemplate ft in query)
                {
                    ftList.Add(ft);
                }
                if (DataEntites.Connection.State != System.Data.ConnectionState.Closed)
                    DataEntites.Connection.Close();
                return ftList;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #region 获取待开单总目录
        /// <summary>
        /// 获取待开单总目录
        /// </summary>
        /// <returns></returns>
        public string GetStartOrderPath()
        {
            try
            {
                FileDirPath fd = DataEntites.FileDirPath.Where(p => p.id == 1).First();
                string startOrderPath = fd.FileDir;
                return startOrderPath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 订单在服务器上的存放总路径
        /// <summary>
        /// 订单在服务器上的存放总路径
        /// </summary>
        /// <returns></returns>
        public string GetOrderStorePath()
        {
            try
            {
                FileDirPath fd = DataEntites.FileDirPath.Where(p => p.id == 2).First();
                string orderStorePath = fd.FileDir;
                return orderStorePath;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        /// <summary>
        /// 获取所有的节点信息
        /// </summary>
        /// <returns></returns>
        public List<tb_Tech> GetAllTech()
        {
            try
            {
                List<tb_Tech> techs = new List<tb_Tech>();
                ObjectQuery<tb_Tech> query = DataEntites.tb_Tech;
                foreach (tb_Tech tech in query)
                {
                    techs.Add(tech);
                }
                return techs;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取所有纸型
        /// </summary>
        /// <returns></returns>
        public List<paperType> GetPaperType()
        {
            try
            {
                List<paperType> paperTypes = new List<paperType>();
                ObjectQuery<paperType> query = DataEntites.paperType;
                foreach (paperType pt in query)
                {
                    paperTypes.Add(pt);
                }
                return paperTypes;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取所有纸面
        /// </summary>
        /// <returns></returns>
        public List<paperFace> GetPaperFace()
        {
            try
            {
                List<paperFace> paperFaces = new List<paperFace>();
                ObjectQuery<paperFace> query = DataEntites.paperFace;
                foreach (paperFace pf in query)
                {
                    paperFaces.Add(pf);
                }
                return paperFaces;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取所有的商户列表
        /// </summary>
        /// <returns></returns>
        public List<Shop> GetShopList()
        {
            try
            {
                List<Shop> ListShop = DataEntites.Shop.Where(p => p.Status == 1).ToList();
                //ObjectQuery<Shop> query = .ToArray();
                //foreach (Shop s in query)
                //{
                //    ListShop.Add(s);
                //}
                return ListShop;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 更新订单包
        /// </summary>
        /// <param name="OrderID"></param>
        /// <param name="OrderBagCode"></param>
        /// <param name="orderName"></param>
        /// <param name="orderPriority"></param>
        /// <param name="shopID"></param>
        /// <param name="orderTime"></param>
        /// <param name="fetchTime"></param>
        /// <returns></returns>
        public Tb_OrderBag UpdateOrderBag(int OrderID, string OrderBagCode, string orderName, int orderPriority, int shopID, DateTime orderTime, DateTime preCompleteTime, string orderRemark, int userId)
        {
            try
            {
                Tb_OrderBag order = DataEntites.Tb_OrderBag.Where("it.OrderBagId=" + OrderID).FirstOrDefault();
                if (order == null)
                {
                    throw new Exception("同一帐号在别处正打开，请退出其它处登陆，重新打开开单界面，再进行开单！");
                }
                order.BagCode = OrderBagCode;
                order.BagName = orderName;
                order.Priority = orderPriority;
                Shop shop = GetShopByShopID(shopID);
                order.Shop = shop;
                order.OrderTime = orderTime;
                order.FetchTime = preCompleteTime;              //取件时间
                order.Status = (int)COM.OrderBagStatus.WaitPhotoMove;
                order.Remark = orderRemark;
                order.users = GetUserByUserId(userId);

                return order;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 根据产品ID获取产品
        /// </summary>
        /// <param name="productID"></param>
        /// <returns></returns>
        public Tb_Product GetProductByProductID(int productID)
        {
            try
            {
                Tb_Product product = DataEntites.Tb_Product.Where("it.ProuctId=" + productID).First();
                return product;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public tb_Tech GetTechByTechID(int techID)
        {
            try
            {
                tb_Tech tech = DataEntites.tb_Tech.Where("it.TechId=" + techID).First();
                return tech;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public List<CommonChargeItem> GetAllCostItems()
        {
            try
            {

                List<CommonChargeItem> itemList = DataEntites.CommonChargeItem.ToList();
                return itemList;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 根据商户ID获取商户
        /// </summary>
        /// <param name="shopID"></param>
        /// <returns></returns>
        public Shop GetShopByShopID(int shopID)
        {
            try
            {
                Shop s = DataEntites.Shop.Where("it.ShopID=" + shopID).First();
                return s;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region 根据userId获取用户
        /// <summary>
        /// 根据userId获取用户
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public users GetUserByUserId(int userId)
        {
            try
            {
                users u = DataEntites.users.Where(p => p.userID == userId).FirstOrDefault();
                return u;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        /// <summary>
        /// 获取指定的订单包
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public Tb_OrderBag GetOrderBag(int orderID)
        {
            try
            {
                Tb_OrderBag order = DataEntites.Tb_OrderBag.Where("it.OrderBagId=" + orderID).FirstOrDefault();
                return order;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取商户特有的参数
        /// </summary>
        /// <param name="shopID"></param>
        /// <param name="productID"></param>
        /// <returns></returns>
        public Shop_Product_Price GetShopPara(int shopID, int productID)
        {
            try
            {
                ObjectQuery<Shop_Product_Price> shops = DataEntites.Shop_Product_Price.Where("it.ShopId=" + shopID + " and it.ProductId=" + productID).Include("paperFace").Include("paperType");
                Shop_Product_Price shop = null;
                if (shops.Count() > 0)
                {
                    shop = shops.First();
                }
                return shop;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region 获取商户产品集合
        /// <summary>
        /// 获取商户产品集合(传统模式稳定后删除)
        /// </summary>
        /// <param name="shopID"></param>
        /// <returns></returns>
        public List<Shop_Product_Price> GetProductShop2(int shopID)
        {
            try
            {
                Shop shop = DataEntites.Shop.Where(s => s.ShopId == shopID).First();
                shop.Shop_Product_Price.Load(MergeOption.OverwriteChanges);
                List<Shop_Product_Price> shopProducts = new List<Shop_Product_Price>();
                foreach (Shop_Product_Price sp in shop.Shop_Product_Price)
                {
                    shopProducts.Add(sp);
                }
                return shopProducts;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        //public  List<ProductCommonItem
        public DataTable GetProductShop(int shopId)
        {
            using (con = new SqlConnection(conStr))
            {
                int delStatus = (int)COM.ProductStatus.Delete;
                try
                {
                    StringBuilder sql = new StringBuilder();
                    sql.Append("select tb_product.ProuctId as ProductId,ProductName,tb_product.Status,UsedTimes,tb_product.Width,tb_product.Height,PageNum,Tb_PorductCategory.ProductCategoryId,ProductCategoryName,");
                    sql.Append(" ProductTypeCode as ProductTypeCode,paperFace.PaperFaceId,paperFace.Name as PaperFaceName,paperType.PaperTypeId,paperType.Name as PaperTypeName,");
                    sql.Append(" mnemonicCode as ZJCode");
                    sql.Append(" from Shop_Product_Price inner join  tb_product on Shop_Product_Price.ProductId=tb_product.ProuctId inner join Tb_PorductCategory on tb_product.ProductCategoryId=Tb_PorductCategory.ProductCategoryId");
                    sql.Append(" inner join tb_ProductType on tb_product.PorductTypeId=tb_ProductType.ProductTypeId");
                    sql.Append(" inner join paperFace on tb_product.paperfaceid=paperFace.paperfaceid");
                    sql.Append(" inner join papertype on tb_product.papertypeid=papertype.papertypeid");
                    sql.Append(" where Shop_Product_Price.shopid=" + shopId + " and tb_product.status!=" + delStatus);
                    SqlCommand cmd = new SqlCommand(sql.ToString(), con);
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    con.Open();
                    adapter.Fill(dt);
                    return dt;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        #endregion
        //public List<ProductCommonItem> GetAllProductCommList()
        //{
        //    List<ProductCommonItem> rtnList = new List<ProductCommonItem>();
        //    using (con = new SqlConnection(conStr))
        //    {
        //        string strSQL = "select Productid,CommonChargeItemId from ProductCommonItem";
        //        SqlCommand cmd = new SqlCommand(strSQL.ToString(), con);
        //        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        //        DataTable dt = new DataTable();
        //        con.Open();
        //        adapter.Fill(dt);
        //        foreach (DataRow dw in dt.Rows)
        //        {
        //            ProductCommonItem pc = new ProductCommonItem();
        //            pc.CommonID = Convert.ToInt32(dw["CommonChargeItemId"]);
        //            pc.ProductID = Convert.ToInt32(dw["Productid"]);
        //            rtnList.Add(pc);
        //        }

        //        return rtnList;
        //    }
        //}

        public DataTable GetProductCommonChange()
        {
            using (con = new SqlConnection(conStr))
            {
                string strSQL = "select Productid,ProductCommonItem.CommonChargeItemId as CommonChargeItemId,ItemName from ProductCommonItem,CommonChargeItem where CommonChargeItem.CommonChargeItemId=ProductCommonItem.CommonChargeItemId";
                SqlCommand cmd = new SqlCommand(strSQL.ToString(), con);
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                con.Open();
                adapter.Fill(dt);
                return dt;
            }
        }
        #region 商户产品使用次数加1
        /// <summary>
        /// 商户产品使用次数加1
        /// </summary>
        public void ProductUseTimeAdd(int productId, int shopId)
        {
            using (con = new SqlConnection(conStr))
            {
                try
                {
                    string sql = "select usedTimes from Shop_Product_Price where ShopId=" + shopId + " and ProductId=" + productId;
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandText = sql;
                    con.Open();
                    int times = 0;
                    if (cmd.ExecuteScalar() != DBNull.Value)
                        times = Convert.ToInt32(cmd.ExecuteScalar());
                    times++;
                    sql = "update Shop_Product_Price set usedtimes=" + times + " where  ShopId=" + shopId + " and ProductId=" + productId;
                    cmd.CommandText = sql;
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        #endregion

        #region 获取某个商户的商户节点员工关系集
        /// <summary>
        /// 获取某个商户的商户节点员工关系集
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public List<MODEL.CustomerManage.StartOrder.ShopTechUser> GetShopTechUser(int shopId)
        {
            try
            {
                List<MODEL.CustomerManage.StartOrder.ShopTechUser> stus = new List<MINERP.MODEL.CustomerManage.StartOrder.ShopTechUser>();
                using (con = new SqlConnection(conStr))
                {
                    string sql = "select ShopId,TechId,shop_tech_user.UserId from shop_tech_user,users where users.userid=shop_tech_user.userid and IsOnline=1 and shopid=" + shopId;
                    SqlCommand cmd = new SqlCommand(sql, con);
                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        MODEL.CustomerManage.StartOrder.ShopTechUser stu = new MINERP.MODEL.CustomerManage.StartOrder.ShopTechUser();
                        stu.ShopId = Convert.ToInt32(reader["ShopId"]);
                        stu.TechId = Convert.ToInt32(reader["TechId"]);
                        stu.UserId = Convert.ToInt32(reader["UserId"]);
                        stus.Add(stu);
                    }
                    reader.Dispose();
                }
                return stus;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取所有员工集合
        /// <summary>
        /// 获取所有员工集合
        /// </summary>
        /// <returns></returns>
        public List<MODEL.CustomerManage.StartOrder.User> GetAllUser()
        {
            try
            {
                List<MODEL.CustomerManage.StartOrder.User> users = new List<MINERP.MODEL.CustomerManage.StartOrder.User>();
                using (con = new SqlConnection(conStr))
                {
                    string sql = "select users.UserId,UserName,TechId,IsOnline from users inner join user_tech on users.userid=user_tech.userid";
                    SqlCommand cmd = new SqlCommand(sql, con);
                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    MODEL.CustomerManage.StartOrder.User nu = new MINERP.MODEL.CustomerManage.StartOrder.User();
                    nu.UserId = 0;
                    nu.UserName = "无";
                    users.Add(nu);
                    while (reader.Read())
                    {
                        MODEL.CustomerManage.StartOrder.User user = new MINERP.MODEL.CustomerManage.StartOrder.User();
                        user.UserId = Convert.ToInt32(reader["UserId"]);
                        user.UserName = Convert.ToString(reader["UserName"]);
                        user.TechId = Convert.ToInt32(reader["TechId"]);
                        user.IsOnline = Convert.ToBoolean(reader["IsOnline"]);
                        users.Add(user);
                    }
                    reader.Dispose();
                }
                return users;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取一个产品所有的委外商
        /// <summary>
        /// 获取一个产品所有的委外商
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public List<MODEL.CustomerManage.StartOrder.ProductOutShop> GetProductOutShop(int productId)
        {
            try
            {
                List<MODEL.CustomerManage.StartOrder.ProductOutShop> pos = new List<MINERP.MODEL.CustomerManage.StartOrder.ProductOutShop>();
                using (con = new SqlConnection(conStr))
                {
                    string sql = "select Tb_OutShop_ProductCategory.OutShopId,ProductId,IsDefaultOutShop,OutShopName from Tb_OutShop_ProductCategory inner join OutProcessShop on Tb_OutShop_ProductCategory.OutShopId=OutProcessShop.OutShopId where ProductId=" + productId;
                    SqlCommand cmd = new SqlCommand(sql, con);
                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        MODEL.CustomerManage.StartOrder.ProductOutShop po = new MINERP.MODEL.CustomerManage.StartOrder.ProductOutShop();
                        po.IsDefaultOutShop = Convert.ToBoolean(reader["IsDefaultOutShop"]);
                        po.OutShopId = Convert.ToInt32(reader["OutShopId"]);
                        po.ProductId = Convert.ToInt32(reader["ProductId"]);
                        po.OutShopName = Convert.ToString(reader["OutShopName"]);
                        pos.Add(po);
                    }
                    reader.Dispose();
                }
                return pos;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取所有委外商
        /// <summary>
        /// 获取所有委外商
        /// </summary>
        /// <returns></returns>
        public List<MODEL.CustomerManage.StartOrder.OutShop> GetAllOutShop()
        {
            try
            {
                List<MODEL.CustomerManage.StartOrder.OutShop> outShops = new List<MINERP.MODEL.CustomerManage.StartOrder.OutShop>();
                using (con = new SqlConnection(conStr))
                {
                    string sql = "select OutShopId,OutShopName from OutProcessShop";
                    SqlCommand cmd = new SqlCommand(sql, con);
                    SqlDataReader reader = cmd.ExecuteReader();
                    con.Open();
                    while (reader.Read())
                    {
                        MODEL.CustomerManage.StartOrder.OutShop os = new MINERP.MODEL.CustomerManage.StartOrder.OutShop();
                        os.OutShopId = Convert.ToInt32(reader["OutShopId"]);
                        os.OutShopName = Convert.ToString(reader["OutShopName"]);
                        outShops.Add(os);
                    }
                    reader.Dispose();
                }
                return outShops;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取所有打印机
        /// <summary>
        /// 获取所有打印机
        /// </summary>
        /// <returns></returns>
        public List<MODEL.CustomerManage.StartOrder.Printer> GetAllPrinter()
        {
            try
            {
                List<MODEL.CustomerManage.StartOrder.Printer> printers = new List<MINERP.MODEL.CustomerManage.StartOrder.Printer>();
                using (con = new SqlConnection(conStr))
                {
                    string sql = "select PrinterId,pname as PrinterName from printer";
                    SqlCommand cmd = new SqlCommand(sql, con);
                    MODEL.CustomerManage.StartOrder.Printer nullP = new MINERP.MODEL.CustomerManage.StartOrder.Printer();
                    nullP.PrinterId = 0;
                    nullP.PrinterName = "无";
                    printers.Add(nullP);
                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        MODEL.CustomerManage.StartOrder.Printer p = new MINERP.MODEL.CustomerManage.StartOrder.Printer();
                        p.PrinterId = Convert.ToInt32(reader["PrinterId"]);
                        p.PrinterName = Convert.ToString(reader["PrinterName"]);
                        printers.Add(p);
                    }
                    reader.Dispose();
                }
                return printers;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 产品的默认打印机
        /// <summary>
        /// 产品的默认打印机
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public int GetProductPrinter(int productId)
        {
            try
            {
                int printerId = 0;
                using (con = new SqlConnection(conStr))
                {
                    string sql = "select PrinterId from product_printer where productid=" + productId;
                    SqlCommand cmd = new SqlCommand(sql, con);
                    con.Open();
                    object obj = cmd.ExecuteScalar();
                    if (obj != DBNull.Value)
                        printerId = Convert.ToInt32(obj);
                }
                return printerId;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 根据outShopId取得委外商
        /// <summary>
        /// 根据outShopId取得委外商
        /// </summary>
        /// <param name="outShopId"></param>
        /// <returns></returns>
        public OutProcessShop GetOutShopByOutShopId(int outShopId)
        {
            try
            {
                return DataEntites.OutProcessShop.Where(p => p.OutShopId == outShopId).First();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取产品已分配的委外商Id
        /// <summary>
        /// 获取产品已分配的委外商Id
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public int GetOutShopIdByOrderProductId(int orderProductId)
        {
            try
            {
                int outShopId = 0;
                using (con = new SqlConnection(conStr))
                {
                    string sql = "select OutShopId from OutProcessRecord where OrderProductId=" + orderProductId;
                    SqlCommand cmd = new SqlCommand(sql, con);
                    con.Open();
                    object obj = cmd.ExecuteScalar();
                    if (obj != DBNull.Value)
                        outShopId = Convert.ToInt32(obj);
                }
                return outShopId;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 取得产品的委外记录
        /// <summary>
        /// 取得产品的委外记录
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public OutProcessRecord GetOutShopRecord(int orderProductId)
        {
            try
            {
                OutProcessRecord record = null;
                record = DataEntites.OutProcessRecord.Where(p => p.orderInfo.OrderProductId == orderProductId).FirstOrDefault();
                return record;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 根据orderProductId取得对应的orderInfo
        /// <summary>
        /// 根据orderProductId取得对应的orderInfo
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public orderInfo GetOrderInfoByOrderProductId(int orderProductId)
        {
            try
            {
                return DataEntites.orderInfo.Where(p => p.OrderProductId == orderProductId).First();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 取得产品对应的打印机
        /// <summary>
        /// 取得产品对应的打印机
        /// </summary>
        /// <param name="orderProductId"></param>
        /// <returns></returns>
        public int GetOrderProductPrinter(int orderProductId)
        {
            try
            {
                int printerId = 0;
                using (con = new SqlConnection(conStr))
                {
                    string sql = "select top 1 printerId from photoInfo where orderproductid=" + orderProductId;
                    SqlCommand cmd = new SqlCommand(sql, con);
                    con.Open();
                    object obj = cmd.ExecuteScalar();
                    if (obj != DBNull.Value)
                        printerId = Convert.ToInt32(obj);
                }
                return printerId;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 刷新指定的产品集合
        /// <summary>
        /// 刷新指定的产品集合
        /// </summary>
        /// <param name="obj"></param>
        public void RefreshPhotoinfo(object obj)
        {
            try
            {
                DataEntites.Refresh(RefreshMode.StoreWins, obj);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region
        /// <summary>
        /// 获取系统时间
        /// </summary>
        /// <returns></returns>
        public DateTime GetServerTime()
        {
            try
            {
                DateTime time = DateTime.Now;
                using (con = new SqlConnection(conStr))
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandText = "Proc_GetDate";
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection = con;
                    con.Open();
                    time = Convert.ToDateTime(cmd.ExecuteScalar());
                }
                return time;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 加载最近2天的CRC码
        public List<string> GetCRCMark()
        {
            try
            {
                List<string> crcMarks = new List<string>();
                DataTable dt = new DataTable();
                using (con = new SqlConnection(conStr))
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    //先删除最近2天以外的CRC码
                    string delSql = "delete from tb_RepeatCheck where CreateTime<'" + DateTime.Now.AddDays(-1) + "'";       //只保留最近2天的CRC码
                    cmd.CommandText = delSql;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    string sql = "select top 10000 photoName from photoinfo";
                    //string sql = "select CRCMark from tb_RepeatCheck";
                    cmd.CommandText = sql;
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    adapter.Fill(dt);
                }
                foreach (DataRow r in dt.Rows)
                {
                    crcMarks.Add(r[0].ToString());
                }
                return crcMarks;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        /// <summary>
        /// 保存数据
        /// </summary>
        public void SaveData()
        {
            DataEntites.SaveChanges();
        }
        /// <summary>
        /// 删除对象
        /// </summary>
        /// <param name="entity"></param>
        public void DelData(object entity)
        {
            DataEntites.DeleteObject(entity);
        }
        /// <summary>
        /// 
        /// 获取收费项目根据名称
        /// </summary>
        /// <param name="inName"></param>
        /// <returns></returns>
        public CommonChargeItem GetItemByName(string inName)
        {
            return DataEntites.CommonChargeItem.FirstOrDefault(p => p.ItemName == inName);
        }

        public List<CommonChargeItem> GetShopCostItems(int id)
        {
            List<CommonChargeItem> listComm = new List<CommonChargeItem>();
            List<Shop_CommonChargeItem_Price> itemList = DataEntites.Shop_CommonChargeItem_Price.Where(p => p.ShopId == id).ToList();
            foreach (Shop_CommonChargeItem_Price list in itemList)
            {
                list.CommonChargeItemReference.Load();
                listComm.Add(list.CommonChargeItem);
            }
            return listComm;
        }
        public List<CommonChargeItem> GetShopCostItems(string inShopName)
        {
            List<CommonChargeItem> listComm = new List<CommonChargeItem>();
            Shop shop = DataEntites.Shop.FirstOrDefault(p => p.shopName == inShopName);
            //List<Shop_CommonChargeItem_Price> itemList = DataEntites.Shop_CommonChargeItem_Price.Where(p => p.s == id).ToList();
            shop.Shop_CommonChargeItem_Price.Load();
            List<Shop_CommonChargeItem_Price> itemList = shop.Shop_CommonChargeItem_Price.ToList(); ;
            foreach (Shop_CommonChargeItem_Price list in itemList)
            {
                list.CommonChargeItemReference.Load();
                listComm.Add(list.CommonChargeItem);
            }
            return listComm;
        }
    }
    
}
